# frozen_string_literal: true

module Wpxf
  module Cli
    # A mixin to provide functions to interact with credentials stored in the database.
    module Creds
      def delete_credential(id)
        item = Wpxf::Models::Credential.first(
          id: id.to_i,
          workspace: active_workspace
        )

        unless item.nil?
          item.destroy
          return print_good "Deleted credential #{id}"
        end

        print_bad "Could not find credential #{id} in the current workspace"
      end

      def list_credentials
        rows = []
        rows.push(
          id: 'ID',
          host: 'Host',
          username: 'Username',
          password: 'Password',
          type: 'Type'
        )

        Wpxf::Models::Credential.where(workspace: active_workspace).each do |cred|
          rows.push(
            id: cred.id,
            host: "#{cred.host}:#{cred.port}",
            username: cred.username,
            password: cred.password,
            type: cred.type
          )
        end

        print_table rows
      end

      def creds(*args)
        return list_credentials if args.length.zero?

        case args[0]
        when '-d'
          delete_credential(args[1])
        else
          print_warning 'Invalid option for "creds"'
        end
      end
    end
  end
end
